package com.ycl.javacore.thread.lock;

import java.util.ArrayList;
import java.util.List;

/**
 * User: OF1089 杨成龙
 * Date: 2019/4/5
 * Time: 5:06 PM
 * Desc: 自定义的可重入锁
 */
public class SelfReentrantLock {
    //是否被锁
    private boolean isLock;
    //被哪个线程锁了
    private Thread lockBy = null;
    //上锁次数
    private int lockedCount = 0;

    public synchronized void lock() throws InterruptedException {
        //如果已经上锁，并且不是当前线上的锁，则当前线程等待
        while (isLock && Thread.currentThread() != lockBy) {
            wait();
        }
        isLock = true;
        lockedCount++;
        lockBy = Thread.currentThread();//当前线程赋值
    }

    public synchronized void unlock() {
        //如果当前线程是已经得到锁的线程，则上锁次数减一次，如果次数到了0，则解锁，唤醒别的线程
        if (Thread.currentThread() == lockBy) {
            lockedCount--;
            if (lockedCount == 0) {
                isLock = false;
                notify();
            }
        }
    }

    public static void main(String[] args) {
        SelfReentrantLock selfReentrantLock = new SelfReentrantLock();
        System.out.println(selfReentrantLock);
        selfReentrantLock.gettest();
    }

    private void gettest() {
        Thread thread = new Thread(() -> {
            System.out.println(this);
        });

        thread.start();
    }
}
